from functools import reduce

# 将字符串转化为浮点数
def proc():
    float_str = '123.456'
    key_map = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': -1}
    float_arr = map(lambda x: key_map[x], float_str)
    point = 0
    def str2float(f, n):
        nonlocal point
        print('f,n={0},{1}    point={2}'.format(f, n, point))
        if n == -1:
            point = 1
            return f

        if point == 0:
            return f * 10 + n
        else:
            point = point * 10
            return f + n / point
    result = reduce(str2float, float_arr)
    print(result)



# 测试使用sort
l = ['ab', 'cc', '2e', 'B', 'P']
def sort_function(n):
    if len(n) >= 2:
        try:
            return int(n)
        except Exception as e:
            return 0
    else:
        return -1


result2 = sorted(l, key=sort_function)
print(result2)

# filter
l = [1, 2, 3, 4, 5, -1, -2, -3, -4]
result = filter(lambda x: x > 0, l)
print(next(result))
for item in result:
    print(item, end=' ')


print('//'*100)

#测试闭包
def f():
    def h(i):
        def g():
            return i * i
        return g
    fs = []
    for i in range(1, 4):
        fs.append(h(i))
    return fs

a, b, c = f()



# 偏函数
print(int('010101010',base=2))
from functools import partial
int2 = partial(int , base=2)
print(int2('010101010'))


# 装饰器
def advance_log(text):
    def decorator(func):
        def wrapper(*args, **kw):
            print('****' * 10, text, func.__name__)
            return func(*args, **kw)
        return wrapper
    return decorator

import functools

# 防止函数签名被篡改
def advance_log2(func):
    @functools.wraps(func)
    def wrapper2(*args, **kw):
        print('****' * 10, func.__name__)
        return func(*args, **kw)
    return wrapper2


@advance_log('adv')
def log(msg):
    print(msg)

log('log_time')
print(log.__name__)

@advance_log2
def log2(msg):
    print(msg)

log2('log_time2')
print(log2.__name__)


# 普通的无参装饰器
def testDec(func):
    def wrapper(*args, **kw):
        print('****')
        return func(*args, **kw)
    return wrapper

@testDec
def dec(msg):
    print(msg)

dec('this is dec')